<template>
  <div ref="page" @click="unfold = false">
    <div class="page-head">
      <CustomTitle title="批量修改商品定价" />
      <el-dropdown>
        <div class="record-list" v-if="!route.query.snapshotId">
          调价记录
          <img src="@/assets/images/record.png" alt="" />
        </div>
        <template #dropdown>
          <el-empty v-if="!recordList.length" image-size="80" style="width: 200px" />
          <el-dropdown-menu style="max-height: 200px">
            <el-dropdown-item v-for="item in recordList" :key="item.snapshotId" @click="command(item.snapshotId)">
              {{ item.title || "未定义" }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class="container">
      <div class="side">
        <el-scrollbar height="calc(100vh - 195px)">
          <Tree :treeData="options" :field="{ key: 'categoryId' }">
            <template #default="{ node }">
              <span @click="addToDraft(node)">{{ node.name }}（{{ node.productNum }}）</span>
              <div class="tag" v-if="node.configStatus">
                {{ ["未配置", "部分配置", "已配置"][node.configStatus] }}
              </div>
            </template>
          </Tree>
        </el-scrollbar>
      </div>
      <div class="content">
        <div class="tip">
          <el-icon> <WarningFilled /> </el-icon
          >温馨提示：京东或天猫线上商品价系数为5，为避免客户认为价格虚高，请尽量不要高于此定价系数
        </div>
        <div class="cacategory-list" ref="list">
          <el-empty v-if="!data.categoryPricingDTOList?.length" />
          <div class="list" v-if="data.categoryPricingDTOList?.length">
            <!-- <el-button
              type="primary"
              style="width: 200px"
              @click="
                () => {
                  console.log('aaaaaaa', data.categoryPricingDTOList);
                }
              "
              >test</el-button
            > -->
            <template v-for="(item, index) in data.categoryPricingDTOList" :key="item.categoryId">
              <div :ref="item.categoryId">
                <PricingItem
                  @openInterval="openInterval"
                  @openSpecial="openSpecial"
                  @delete="deleteItem"
                  @changeCoefficient="saveCoefficient"
                  :data="item"
                  :edit="!!route.query.snapshotId"
                />
              </div>
              <div class="divider" v-if="index !== data.categoryPricingDTOList.length - 1"></div>
            </template>
          </div>
        </div>
      </div>
    </div>
    <div class="comfirm" v-if="data.categoryPricingDTOList?.length && isSubmit" :style="{ width: width + 40 + 'px' }" @click.stop>
      <el-space>
        <div class="comfirm-title">调价平均总毛利率</div>
        <Record :data="data" />
        <div class="black">
          被调正价商品（{{ data.normalPriceProductNum || 0 }}） 被调特价商品（{{ data.specialPriceProductNum || 0 }}）
        </div>
        <span class="blue" @click="unfold = !unfold"
          >展开
          <el-icon v-if="!unfold">
            <CaretTop />
          </el-icon>
          <el-icon v-else>
            <CaretBottom />
          </el-icon>
        </span>
      </el-space>
      <el-space>
        <el-button type="primary" @click="comfirmSave = true" v-if="isSubmit && !route.query.snapshotId">确认并提交</el-button>
      </el-space>
      <transition name="el-zoom-in-bottom">
        <div class="unfold" v-if="unfold" :style="{ width: width + 40 + 'px' }">
          <Record @click="to(item.categoryId)" v-for="item in data.categoryPricingDTOList" :data="item" />
        </div>
      </transition>
    </div>
    <AddInterval
      v-model:show="interval"
      v-if="interval"
      :data="intervalIndex >= 0 ? data.categoryPricingDTOList[intervalIndex] : {}"
      @comfirm="addIntervalItem"
    />
    <AddSpecial
      v-model:show="special"
      v-if="special"
      :data="specialIndex >= 0 ? data.categoryPricingDTOList[specialIndex].specGroupList[specialItemIndex] : {}"
      :categoryId="data.categoryPricingDTOList[specialIndex].categoryId"
      :edit="!!route.query.snapshotId"
      @comfirm="addSpecialItem"
    />
    <el-dialog v-model="comfirmSave" width="500px" center align-center @close="submitRef.resetFields()">
      <template #title>
        <CustomTitle title="定价草稿确认更新提醒" />
      </template>
      <div class="tip-content">
        <el-icon>
          <Warning />
        </el-icon>
        <div class="text">为了避免您对商品价格变更中的误操作，价格更新后会立刻生效，请确认是否对本次价格的调整更新~~</div>
        <div class="name">
          <div>为了方便您更好的管理查询调价记录，请输入名称标题！</div>
          <el-form ref="submitRef" :model="submitForm" :rules="submitRules">
            <el-form-item label="名称标题" prop="title">
              <div class="input">
                <el-input v-model="submitForm.title" placeholder="请输入"></el-input>
                {{ submitForm.timestamp }}
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <el-button @click="comfirmSave = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import CustomTitle from "@/components/CustomTitle/index.vue";
import Tree from "./components/Tree.vue";
import PricingItem from "./components/PricingItem.vue";
import { ref, onMounted, getCurrentInstance, nextTick } from "vue";
import { useElementSize } from "@vueuse/core";
import Record from "./components/Record.vue";
import AddInterval from "./components/AddInterval.vue";
import AddSpecial from "./components/AddSpecial.vue";
import {
  getCategory,
  getDraftList,
  getRecord,
  saveDraft,
  submitDraft,
  getAllGrossMargin,
  getPricingConfig,
  getDetail,
  saveShopCoefficient
} from "@/apis/pricing";
import { ElMessage } from "element-plus";
import { useDateFormat, useNow } from "@vueuse/core";
import { useThrottleFn } from "@vueuse/core";
import { useRouter, useRoute } from "vue-router";

const route = useRoute();
const router = useRouter();
const submitRef = ref(null);
const page = ref(null);
const { width } = useElementSize(page);
const { proxy } = getCurrentInstance();
const comfirmSave = ref(false);
const options = ref([]);
const currentId = ref();
const unfold = ref(false);
const data = ref({});
const interval = ref(false);
const special = ref(false);
const recordList = ref([]);
const intervalIndex = ref(-1);
const specialIndex = ref(-1);
const specialItemIndex = ref(-1);
const submitRules = {
  title: [
    { required: true, message: "请输入名称标题" },
    { max: 20, message: "名称标题长度不能超过20个字符" }
  ]
};

/**保存定价系数（V0.8.6） */
const saveCoefficient = (val, data) => {
  console.log("这是要保存的定价系数===", val, data.categoryId);
  saveShopCoefficient({
    categoryId: data.categoryId,
    coefficient: val
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "定价系数修改成功",
        type: "success"
      });
      getDraftDataList(true);
    }
  });
};
const openInterval = item => {
  interval.value = true;
  intervalIndex.value = data.value.categoryPricingDTOList.findIndex(v => v.categoryId === item.categoryId);
};
const openSpecial = (item, index) => {
  special.value = true;
  specialIndex.value = data.value.categoryPricingDTOList.findIndex(v => v.categoryId === item.categoryId);
  specialItemIndex.value = index;
};
const submitForm = ref({
  title: "",
  timestamp: useDateFormat(useNow(), "YYYYMMDDHHmmss")
});
/**提交 */
const submit = async () => {
  submitRef.value.validate(async valid => {
    if (!valid) return;
    const res = await submitDraft({ title: submitForm.value.title + submitForm.value.timestamp });
    if (res.code == 200) {
      comfirmSave.value = false;
      ElMessage.success("提交成功");
      getDraftDataList();
      getRecordList();
    }
  });
};
/**获取总毛利率 */
const getAllGrossMarginData = async () => {
  const res = await getAllGrossMargin(data.value);
  data.value = { ...data.value, ...res.data };
};
/**
 * 保存
 */
const save = async (isTip = true) => {
  await getAllGrossMarginData();
  try {
    const res = await saveDraft(data.value);
    if (res.code == 200) {
      getDraftDataList();
      isSubmit.value = isTip;
      if (isTip) ElMessage.success("操作成功");
      interval.value = false;
      special.value = false;
    }
  } catch (error) {
    getDraftDataList();
  }
};
/**
 * 获取分类列表
 */
const getCategoryList = async () => {
  const res = await getCategory();
  options.value = res.data;
  getConfigId();
};
const categoryId = ref("");
const getConfigId = () => {
  const traverse = tree => {
    for (let v of tree) {
      if (v.configurationType) {
        categoryId.value = v.categoryId;
        return;
      } else if (v.children && v.children.length) {
        traverse(v.children);
      }
    }
  };
  traverse(options.value);
};
const isSubmit = ref(true);
/**
 * 获取草稿列表
 */
const getDraftDataList = async isget => {
  const res = await getDraftList();
  if (res.data.categoryPricingDTOList.length == 0 && isget) {
    isSubmit.value = false;
    if (categoryId.value) {
      const result = await getPricingConfig(categoryId.value);
      data.value = result.data;
      if (data.value.categoryPricingDTOList.length) save(false);
    }
  } else {
    isSubmit.value = true;
    data.value = res.data;
  }
};
/**
 * 获取调价记录列表
 */
const getRecordList = async () => {
  const res = await getRecord();
  recordList.value = res.data;
};
/**
 * 查看历史记录
 */
const command = async snapshotId => {
  const routeInfo = router.resolve({
    path: "/products/pricing",
    query: { snapshotId }
  });
  const url = routeInfo.href;
  window.open(url, "_blank");
};
const to = categoryId => {
  proxy.$refs.list.scroll({
    top: proxy.$refs[categoryId][0].offsetTop - 100,
    behavior: "smooth"
  });
};
/**
 * 将左侧分类添加到草稿
 */
const addToDraft = useThrottleFn(async node => {
  if (data.value.categoryPricingDTOList?.some(item => item.categoryId === node.categoryId)) {
    to(node.categoryId);
    return;
  }
  if (!route.query.snapshotId) {
    const categoryNameList = getCategoryNameList(node.categoryId);
    let oldConfig = {};
    if (node.configStatus != 0) {
      const res = await getPricingConfig(node.categoryId);
      oldConfig = res.data.categoryPricingDTOList[0] || {};
    }
    const item = Object.keys(oldConfig).length ? oldConfig : { categoryId: node.categoryId, categoryNameList };
    if (data.value.categoryPricingDTOList?.length) {
      data.value.categoryPricingDTOList.push(item);
    } else {
      data.value.categoryPricingDTOList = [item];
    }
    nextTick(() => to(node.categoryId));
    save();
  }
}, 1000);
/**
 * 删除
 */
const deleteItem = async node => {
  data.value.categoryPricingDTOList = data.value.categoryPricingDTOList.filter(item => item.categoryId !== node.categoryId);
  save();
};
/**
 * 递归获取名称数组
 */
const getCategoryNameList = id => {
  let arr = [];
  const traverse = tree => {
    for (const v of tree) {
      if (v.categoryId == id) {
        arr.unshift(v.name);
        return v.name;
      } else if (v.children && v.children.length) {
        if (traverse(v.children)) {
          arr.unshift(v.name);
          return v.name;
        }
      }
    }
    return null;
  };
  traverse(options.value);
  return arr;
};
/**
 * 添加常规定价
 */
const addIntervalItem = form => {
  if (form.length) {
    data.value.categoryPricingDTOList[intervalIndex.value].normalPricing = {
      ...data.value.categoryPricingDTOList[intervalIndex.value].normalPricing,
      pricingList: form,
      pricingType: 0
    };
  } else {
    delete data.value.categoryPricingDTOList[intervalIndex.value].normalPricing;
  }
  save();
};
/**
 * 添加特殊定价
 */
const addSpecialItem = form => {
  const index = data.value.categoryPricingDTOList[specialIndex.value].specGroupList.findIndex(
    v => v.assemblyId == form.assemblyId
  );
  if (index == -1) {
    data.value.categoryPricingDTOList[specialIndex.value].specGroupList.push(form);
  } else {
    data.value.categoryPricingDTOList[specialIndex.value].specGroupList[index] = form;
  }
  data.value.categoryPricingDTOList[specialIndex.value].specGroupList = data.value.categoryPricingDTOList[
    specialIndex.value
  ].specGroupList.filter(v => v.pricingList.length);
  save();
};
onMounted(async () => {
  await getCategoryList();
  if (route.query.snapshotId) {
    const res = await getDetail(route.query.snapshotId);
    data.value = res.data;
  } else {
    getDraftDataList(true);
    getRecordList();
  }
});
</script>
<style lang="scss" scoped>
@import "index.scss";
</style>
